<template>
  <div>
    <el-menu-item
      v-if="hasOneChild(item.children, item)"
      :index="getPath(oneChild.path)"
    >
      <i class="el-icon-menu" />
      <span slot="title">{{ oneChild.name }}</span>
    </el-menu-item>
    <el-submenu v-else :index="getPath(item.path)">
      <template slot="title">
        <i class="el-icon-location" />
        <span slot="title">{{ item.name }}</span>
      </template>
      <menu-item
        v-for="child in item.children"
        :key="child.path"
        :item="child"
        :basepath="getPath(item.path)"
      />
    </el-submenu>
  </div>
</template>
<script>
import path from 'path'
export default {
  name: 'MenuItem',
  props: {
    item: {
      type: Object,
      required: true
    },
    basepath: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      oneChild: ''
    }
  },
  methods: {
    hasOneChild(children, parent) {
      // console.log('-----childeren', children)
      if (!children || children.length === 0) {
        // 没有子菜单
        this.oneChild = {
          ...parent,
          children: []
        }
        return true
      } else if (children.length === 1) {
        // 只有一个子菜单
        this.oneChild = children[0]
        return true
      }

      return false
    },
    getPath(url) {
      return path.resolve(this.basepath, url)
    }
  }
}
</script>

<style></style>
